package com.kt.controller;

import com.kt.VO.ResultVO;
import com.kt.converter.OrderForm2OrderDTOConverter;
import com.kt.dto.OrderDTO;
import com.kt.enums.ResultEnum;
import com.kt.exception.OrderException;
import com.kt.form.OrderForm;
import com.kt.service.OrderService;
import com.kt.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lenovo on 2019/1/12.
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController  {
    /**
     * 1. 参数检验
     * 2. 查询商品信息(调用商品服务)
     * 3. 计算总价
     * 4. 扣库存(调用商品服务)
     * 5. 订单入库
     */
@Autowired
private OrderService orderService;
    //@Valid 用于验证注解是否符合要求，直接加在变量orderForm之前，
    // 在变量中添加验证信息的要求，
    //当不符合要求时就会在方法中返回message的错误提示信息。
    @PostMapping("/create")
    public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info("{创建订单}");
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO= OrderForm2OrderDTOConverter.convert(orderForm);
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("创建订单为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }

        OrderDTO result=orderService.create(orderDTO);
        Map<String,String > map=new HashMap<>();
        map.put("orderId",result.getOrderId());
        return ResultVOUtil.success(map);
    }
}
